#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
修复MediaPipe资源文件缺失问题的打包脚本
"""

import os
import sys
import subprocess
import shutil
from pathlib import Path

def find_mediapipe_resources():
    """查找MediaPipe资源文件路径"""
    try:
        import mediapipe as mp
        # 获取MediaPipe安装路径
        mp_path = os.path.dirname(mp.__file__)
        print(f"MediaPipe安装路径: {mp_path}")
        
        # 常见的资源文件路径
        resource_paths = [
            os.path.join(mp_path, 'modules'),
            os.path.join(mp_path, 'assets'),
            os.path.join(mp_path, 'python/modules'),
        ]
        
        found_resources = []
        for path in resource_paths:
            if os.path.exists(path):
                found_resources.append(path)
                print(f"找到资源目录: {path}")
        
        return found_resources
    except ImportError:
        print("未找到MediaPipe库")
        return []

def create_fixed_spec_file():
    """创建修复资源文件问题的spec文件"""
    # 查找MediaPipe资源
    mediapipe_resources = find_mediapipe_resources()
    
    spec_content = '''# -*- mode: python ; coding: utf-8 -*-

import sys
import os
from PyInstaller.utils.hooks import collect_data_files

# 添加当前目录到路径
sys.path.append(os.path.dirname(os.path.abspath('.')))

# 收集MediaPipe数据文件
mediapipe_datas = collect_data_files('mediapipe')

block_cipher = None

a = Analysis(
    ['gui_app.py'],
    pathex=[],
    binaries=[],
    datas=[
        ('config.py', '.'),
        ('analysis/*.py', 'analysis'),
        ('core/*.py', 'core'),
        ('data/*.py', 'data'),
        ('video/*.py', 'video'),
        ('model/*', 'model'),
    ] + mediapipe_datas,  # 添加MediaPipe资源文件
    hiddenimports=[
        'tkinter',
        'tkinter.ttk',
        'tkinter.filedialog',
        'cv2',
        'cv2.data',
        'numpy',
        'PIL',
        'PIL.Image',
        'PIL.ImageTk',
        'matplotlib',
        'matplotlib.backends.backend_tkagg',
        'pandas',
        'mediapipe',
        'mediapipe.solutions',
        'mediapipe.solutions.face_mesh',
        'mediapipe.solutions.drawing_utils',
        'mediapipe.solutions.drawing_styles',
        'mediapipe.modules.face_landmark.face_landmark_front_cpu',
        'mediapipe.modules.face_geometry.face_geometry_cpu',
        'mediapipe.modules.face_detection.face_detection_front_cpu',
    ],
    hookspath=[],
    hooksconfig={},
    runtime_hooks=[],
    excludes=[],
    win_no_prefer_redirects=False,
    win_private_assemblies=False,
    cipher=block_cipher,
    noarchive=False,
)

pyz = PYZ(a.pure, a.zipped_data, cipher=block_cipher)

exe = EXE(
    pyz,
    a.scripts,
    a.binaries,
    a.zipfiles,
    a.datas,
    [],
    name='面部表情分析系统',
    debug=False,
    bootloader_ignore_signals=False,
    strip=False,
    upx=True,
    upx_exclude=[],
    runtime_tmpdir=None,
    console=False,
    disable_windowed_traceback=False,
    argv_emulation=False,
    target_arch=None,
    codesign_identity=None,
    entitlements_file=None,
    icon='model/face.ico' if os.path.exists('model/face.ico') else None
)
'''
    
    with open('face_analysis_fixed.spec', 'w', encoding='utf-8') as f:
        f.write(spec_content)
    print("已创建修复版spec文件: face_analysis_fixed.spec")

def create_manual_copy_script():
    """创建手动复制资源文件的脚本"""
    script_content = '''@echo off
cls
echo ========================================
echo 面部表情分析系统 - MediaPipe资源文件修复
echo ========================================

echo.
echo 步骤1: 激活conda环境
call conda activate pretreatment

echo.
echo 步骤2: 安装PyInstaller
pip install pyinstaller

echo.
echo 步骤3: 构建可执行文件
python -m PyInstaller --noconfirm --windowed --name "面部表情分析系统" gui_app.py

echo.
echo 步骤4: 手动复制MediaPipe资源文件
echo 请手动执行以下步骤：
echo 1. 找到MediaPipe安装目录 (通常在 conda envs\\pretreatment\\Lib\\site-packages\\mediapipe)
echo 2. 复制 modules 目录到 dist\\面部表情分析系统\\_internal\\mediapipe\\
echo 3. 复制 assets 目录到 dist\\面部表情分析系统\\_internal\\mediapipe\\ (如果存在)
echo.
echo 或者运行: python fix_mediapipe_resources.py
pause
'''
    
    with open('fix_mediapipe_resources.bat', 'w', encoding='utf-8') as f:
        f.write(script_content)
    print("已创建资源文件修复脚本: fix_mediapipe_resources.bat")

def create_resource_copy_script():
    """创建自动复制资源文件的脚本"""
    py_script = '''#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
自动复制MediaPipe资源文件的脚本
"""

import os
import sys
import shutil
from pathlib import Path

def copy_mediapipe_resources():
    """复制MediaPipe资源文件到打包目录"""
    try:
        import mediapipe as mp
        # 获取MediaPipe安装路径
        mp_path = Path(mp.__file__).parent
        print(f"MediaPipe路径: {mp_path}")
        
        # 目标路径
        target_base = Path("dist/面部表情分析系统/_internal/mediapipe")
        target_base.mkdir(parents=True, exist_ok=True)
        
        # 需要复制的目录
        source_dirs = ["modules", "assets"]
        
        for dir_name in source_dirs:
            source_path = mp_path / dir_name
            if source_path.exists():
                target_path = target_base / dir_name
                print(f"复制 {source_path} 到 {target_path}")
                if target_path.exists():
                    shutil.rmtree(target_path)
                shutil.copytree(source_path, target_path)
                print(f"✓ {dir_name} 复制完成")
            else:
                print(f"- {dir_name} 不存在，跳过")
        
        print("\\n🎉 MediaPipe资源文件复制完成！")
        return True
    except Exception as e:
        print(f"❌ 复制过程中出错: {e}")
        return False

if __name__ == "__main__":
    copy_mediapipe_resources()
'''
    
    with open('fix_mediapipe_resources.py', 'w', encoding='utf-8') as f:
        f.write(py_script)
    print("已创建资源文件复制脚本: fix_mediapipe_resources.py")

def build_with_fixed_resources():
    """使用修复的配置进行构建"""
    print("开始使用修复配置构建...")
    
    # 创建修复版spec文件
    create_fixed_spec_file()
    
    try:
        # 使用spec文件构建
        cmd = [sys.executable, "-m", "PyInstaller", "face_analysis_fixed.spec"]
        print("执行命令:", " ".join(cmd))
        subprocess.check_call(cmd)
        print("✓ 构建成功完成！")
        return True
    except subprocess.CalledProcessError as e:
        print(f"✗ 构建失败: {e}")
        return False
    except Exception as e:
        print(f"✗ 构建过程中发生错误: {e}")
        return False

def main():
    """主函数"""
    print("面部表情分析系统 - MediaPipe资源文件修复工具")
    print("=" * 50)
    
    # 创建辅助脚本
    create_manual_copy_script()
    create_resource_copy_script()
    
    print("\\n已创建以下辅助文件:")
    print("1. fix_mediapipe_resources.bat - 手动修复脚本")
    print("2. fix_mediapipe_resources.py - 自动复制资源文件脚本")
    print("3. face_analysis_fixed.spec - 修复版spec配置文件")
    
    if len(sys.argv) > 1 and sys.argv[1] == "build":
        print("\\n开始构建...")
        if build_with_fixed_resources():
            print("\\n🎉 打包成功完成！")
            print("可执行文件位于 dist/面部表情分析系统/ 目录中")
        else:
            print("\\n❌ 打包失败")
            print("请尝试手动复制资源文件:")
            print("1. 运行 fix_mediapipe_resources.py")
            print("2. 或手动复制MediaPipe的modules和assets目录")
        return
    
    print("\\n使用方法:")
    print("1. 自动构建: python fix_mediapipe_build.py build")
    print("2. 手动修复: 运行 fix_mediapipe_resources.bat")
    print("3. 自动复制: python fix_mediapipe_resources.py")
    
    print("\\n说明:")
    print("- MediaPipe需要额外的二进制资源文件才能正常工作")
    print("- PyInstaller默认不会包含这些文件")
    print("- 我们提供了多种解决方案来处理这个问题")

if __name__ == "__main__":
    main()